/**
 * 添加或者修改页面
 */
var IndentOrderInfoDlg = {
    data: {
        indentOrderNum: "",
        dealer: "",
        purchaseId: "",
        time: "",
        checkCode: "",
        remark: ""
    }
};

layui.use(['form', 'admin', 'ax', 'layedit', 'table', 'tableSelect', 'layer'], function () {
    var $ = layui.jquery;
    var $ax = layui.ax;
    var form = layui.form;
    var admin = layui.admin;
    var layedit = layui.layedit;
    var lay_table = layui.table;
    var table_select = layui.tableSelect;
    var layer = layui.layer;

    //让当前iframe弹层高度适应
    admin.iframeAuto();

    //表格
    lay_table.render({
        elem: '#purchaseDetail'
        , toolbar: '#toolbar'
        , title: '用户数据表'
        , cellMinWidth: 100
        , totalRow: true
        , data: []
        , cols: [[
            {type: 'numbers', title: '序号', rowspan: 2, fixed: 'left'},
            {field: 'id', title: '产品ID', hide: true, rowspan: 2},
            {
                field: 'productName',
                title: '产品大类',
                totalRowText: '合计'
            }, {field: 'productModelName', sort: true, title: '产品型号'},
            {field: 'productOrderName', sort: true, title: '产品品号'},
            {field: 'color', sort: true, title: '产品颜色'},
            {field: 'colorNumber', hide: true, sort: true, title: '产品色号'},
            {field: 'material', sort: true, hide: true, title: '产品材质'},
            {field: 'price', sort: true, title: '价格'},
            {field: 'conversionRatio', sort: true, title: '换算比率'},
            {field: 'unitName', title: '产品单位', event: 'setUnit', rowspan: 2},
            {field: 'unitId', title: '产品单位id', hide: true},
            {field: 'packageSize', sort: true, hide: true, title: '包装尺寸'},
            {field: 'unitVolume', sort: true, hide: true, title: '体积'},
            {field: 'unitWeight', sort: true, hide: true, title: '净重'},
            {field: 'unitVolumeUse', sort: true, title: '体积'},
            {field: 'unitWeightUse', sort: true, title: '净重'},
            {field: 'channel', sort: false, hide: true, title: '渠道'},
            {
                field: 'orderNumbers',
                title: '采购数量',
                rowspan: 2,
                fixed: 'right',
                totalRow: true,
                edit: "number",
                default: 1
            },

            {
                field: 'orderAmount',
                fixed: 'right',
                title: '金额',
                rowspan: 2,
                align: 'center',
                totalRow: true
            },
            {field: 'remark', hide: true},
            {fixed: 'right', align: 'center', title: '操作', rowspan: 2, toolbar: '#tableBar'}
        ]
        ],
        page: false
    });

    //监听单元格编辑
    lay_table.on('edit(productTable)', function (obj) {
        var value = obj.value; //得到修改后的值
        var data = obj.data;
        obj.update({
            orderAmount: getAmount(data.orderNumbers, data.price, 2),
            unitVolumeUse: getUnitVolume(data.unitVolume, data.orderNumbers, 2),
            unitWeightUse: getUnitWeight(data.unitWeight, data.orderNumbers, 2)
        });
        lay_table.reload('purchaseDetail', {
            data: lay_table.cache['purchaseDetail']
        });
    });

    function getAmount(orderNumbers, price, decimal) {
        if (!isNaN(orderNumbers) && !isNaN(price)) {
            return parseFloat(orderNumbers) * parseFloat(price).toFixed(decimal);
        }
    }

    //获取多台总体积
    function getUnitVolume(unitVolume, orderNumbers, deciaml) {
        if (!isNaN(unitVolume) && !isNaN(orderNumbers)) {
            return parseFloat(unitVolume) * parseFloat(orderNumbers).toFixed(deciaml);
        }
    }

    function getUnitWeight(unitWeight, orderNumbers, decimal) {
        if (!isNaN(unitWeight) && !isNaN(orderNumbers)) {
            return parseFloat(unitWeight) * parseFloat(orderNumbers).toFixed(decimal);
        }
    }


    lay_table.on('tool(productTable)', function (obj) {
        var data = obj.data;

        switch (obj.event) {
            case "del":
                layer.confirm('are you 确定?', function (index) {
                    obj.del();
                    layer.close(index);
                });
                break;
            case "remark":
                layer.prompt({
                    formType: 2,
                    value: data.remark,
                    title: '备注',
                    area: ['500px', '200px'] //自定义文本域宽高
                }, function (value, index, elem) {
                    obj.update({
                        remark: value
                    });

                    layer.close(index);
                });
                break;
            case "setUnit":
                layer.open({
                    title: "⚙ 单位选择",
                    type: 2,
                    skin: 'layui-layer-admin',
                    content: Feng.ctxPath + '/unit/unitsByProductId?productId=' + data.id, //这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content: ['http://sentsin.com', 'no']
                    area: ['500px', '205px'],
                    end: function () {
                        var unit = admin.getTempData('ok');
                        console.log(unit);
                        console.log(unit.id);
                        obj.update({
                            unitName: unit.name,
                            unitId: unit.id,
                            orderAmount: getAmount(data.conversionRatio, data.unitId, data.orderNumbers, data.price)
                        });
                        console.log(getAmount(data.conversionRatio, data.id, data.orderNumbers, data.price));
                        lay_table.reload('purchaseDetail', {
                            data: lay_table.cache['purchaseDetail']
                        });
                    }, cancel: function () {
                        obj.update({
                            unitsId: data.unitsId,
                            orderAmount: getAmount(data.orderNumbers, data.price)
                        });
                        lay_table.reload('purchaseDetail', {
                            data: lay_table.cache['purchaseDetail']
                        });
                    }
                });
                break;
        }
    });


    //头工具栏事件
    lay_table.on('toolbar(productTable)', function (obj) {
        var data = obj.data;
        var checkStatus = lay_table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'add':
                top.layui.admin.open({
                    type: 2,
                    area: ["100%", "100%"],
                    title: '产品添加',

                    content: Feng.ctxPath + '/table_select/product_table_select',
                    end: function () {
                        var oldData = lay_table.cache['purchaseDetail'];
                        var list = admin.getTempData('product_list');
                        for (var i = 0; i < list.length; i++) {
                            oldData.push(list[i]);
                        }

                        lay_table.reload('purchaseDetail', {
                            data: oldData
                        });
                    }, cancel: function () {
                        admin.putTempData("product_list", null);
                    }
                });
                break;
            case 'getCheckLength':
                var data = checkStatus.data;
                layer.msg('选中了：' + data.length + ' 个');
                break;
            case 'isAll':
                layer.msg(checkStatus.isAll ? '全选' : '未全选');
                break;
        }
    });


    //表单提交事件
    form.on('submit(btnSubmit)', function (data) {

                if(confirm("满10个方有礼品赠送!")){
                    var ajax = new $ax(Feng.ctxPath + "/purchaseOrders/submit", function (data) {
                        Feng.success("添加成功!");
                        window.location.href = Feng.ctxPath + "/indentOrder";
                        //传给上个页面，刷新table用
                        admin.putTempData('formOk', true);

                        //关掉对话框
                        admin.closeThisDialog();
                    }, function (data) {
                        window.location.href = Feng.ctxPath + "/indentOrder";
                        /*Feng.error("添加失败！" + data.responseJSON.message)*/
                    });
                    var productDetail = lay_table.cache['purchaseDetail'];

                    var requestData = [];

                    var errorInfo = "";

                    /* //数据验证
                     productDetail.forEach(function (value, index, array) {
                         if (value.orderNumbers === 0) {
                             errorInfo += "产品:" + value.productName + "采购数量为0或未填写 ! \n "
                         }
                         if (value.unitsId === null) {
                             errorInfo += "产品:" + value.productName + "单位未填写 ! \n "
                         }
                     });*/

                    if (productDetail.length === 0) {
                        Feng.error("请添加产品!");
                        return false;
                    }

                    productDetail.forEach(function (val, index, arr) {
                        var product = {};
                        product.productId = val.id;
                        product.unitId = val.unitId;
                        product.orderNumbers = val.orderNumbers;
                        product.orderAmount = val.orderAmount;
                        product.remark = val.remark;
                        product.unitMax = val.unitMax;
                        product.unitMin = val.unitMin;
                        product.price = val.price;
                        product.conversionRatio = val.conversionRatio;

                        requestData.push(product);
                    });

                    console.log(JSON.stringify(requestData));
                    data.field['purchaseDetail'] = JSON.stringify(requestData);
                    ajax.set(data.field);
                    ajax.start();

                    return false;

                }else{

                }




    });

    //返回按钮
    $("#backPage").click(function () {
        window.location.href = Feng.ctxPath + '/indentOrder'
    });

});